#include <iostream>
#include <unistd.h>
#include <stdio.h>
#include <string>
#include <cerrno>
#include <fcntl.h>

void setNonBlock(int fd)
{
    int fl = ::fcntl(fd, F_GETFL);
    if (fl < 0)
    {
        perror("fcntl");
        return;
    }
    ::fcntl(fd, F_SETFL, fl | O_NONBLOCK); // 让该fd进行非阻塞调用
}
int main()
{
    char buffer[1024];
    std::string tips = "Please enter# ";
    setNonBlock(0);
    while (true)
    {
        int n = ::read(0, buffer, sizeof buffer);
        if (n > 0)
        {
            write(0, tips.c_str(), tips.size());
            buffer[n] = 0;
            std::cout << "echo# " << buffer << std::endl;
        }

        else
        {
            if (errno == EINTR)
            {
                std::cout << "被中断，重新来" << std::endl;
                continue;
            }
            else if (errno == EAGAIN || errno == EWOULDBLOCK)
            {
                std::cout << "底层数据没有就绪" << std::endl; 
                continue;
            }
            else if (n == 0)
            {
                std::cout << "read end file!" << std::endl;
                continue;
            }
            std::cout << "read error: " << n << " erron:" << errno << std::endl;
        }
        sleep(1);
    }

    return 0;
}
